import { Data, Render } from "#fansky";
import fetch from "node-fetch";
import GsCfg from "../../../genshin/model/gsCfg.js";

let Ranking = {
    async renderData(e, uid, result) {
        if (e.isGroup) {
            await this.groupRank(e, uid, result);
        }
        let { name, sign } = await this.requestPlayer(uid)
        let data = {
            ...result,
            uid,
            name,
            sign,
            box: e.box,
            saveId: uid,
            qq: e.at || e.user_id
        }
        if (!e.box) {
            data.achievement = await this.getAchievement().achievement;
        }
        return await Render.render(e, 'tops/rank', data);
    },

    async groupRank(e, uid, result) {
        if (/\d+/g.test(e.msg)) return
        let user = e.at || e.user_id;
        let mode = e.box ? 'chest' : 'achieve';
        try {
            let data = await Data.readJSON(`${e.group_id}.json`, 'data')
            if (!data[mode]) {
                data[mode] = { }
            }
            // 判断数据长度是否等于20
            if (Object.keys(data[mode]).length === 20) {
                // 对数据进行排序
                let sortData = Object.values(data[mode]).sort((a, b) => b.grade - a.grade);
                // 判断最后一个数据的grade是否小于result.grade
                let last = sortData[sortData.length - 1]
                if (last.grade < result.grade) {
                    // 进行替换
                    delete data[mode][last];
                    data[mode][user] = result;
                } else {
                    // 直接返回
                    return;
                }
            } else {
                // 数据长度不等于20，直接写入
                data[mode][user] = result;
            }
            // 补充 uid , result 没有 uid 数据
            data[mode][user].uid = uid;
            return await Data.writeJSON(`${e.group_id}.json`, data, 'data')
        } catch (err) {
            logger.error(err)
            return e.reply(`获取或更新群${e.box ? '宝箱' : '成就'}排名失败~`, true)
        }
    },

    async requestPlayer(uid) {
        try {
            const response = await fetch(`https://enka.network/api/uid/${uid}?info`, {
                method: 'GET',
                headers: {
                    "Content-Type": "application/json",
                }
            });
            let { playerInfo } = await response.json();
            if (!playerInfo) {
                return { name: '出厂设置', sign: 'w太懒了！没有签名喵~' };
            }
            const { nickname, signature } = playerInfo;
            return { name: nickname, sign: signature || 'w太懒了！没有签名喵~' };
        } catch (error) {
            const errorMessages = {
                'status code 424': '该服接口正在维护',
                'timeout': '超时惹~'
            };
            const errorMessage = Object.entries(errorMessages).find(([key]) => error.toString().includes(key));
            if (!errorMessage) {
                logger.error(`请求出错惹！ ${error}`);
            }
            const errorInfo = errorMessage ? errorMessage[1] : 'Error惹~';
            return { name: errorInfo, sign: errorInfo };
        }
    },

    async getAchievement() {
        return GsCfg.getdefSet('role', 'index');
    }
}

export default Ranking
